﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using MCServerHelper.Services;

namespace MCServerHelper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                _minecraft = new MinecraftServer();
                _minecraft.OutputReceived += new EventHandler<EventArgs<string>>(_minecraft_OutputReceived);

                _minecraft.Services.Add(new BackupService());
                _minecraft.Services.Add(new MotdService());
                _minecraft.Start();
            }
        }

        private void _minecraft_ErrorReceived(object sender, EventArgs<string> e)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                outputBox.Text += e.Value;
                outputBox.Text += Environment.NewLine;
                outputScroll.ScrollToEnd();
            }));
        }

        private void _minecraft_OutputReceived(object sender, EventArgs<string> e)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                outputBox.Text += e.Value;
                outputBox.Text += Environment.NewLine;
                outputScroll.ScrollToEnd();
            }));
        }

        private MinecraftServer _minecraft = null;

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            _minecraft.ForceStop();
            base.OnClosing(e);
        }

        public static RoutedCommand SendInput = new RoutedCommand();

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = !string.IsNullOrEmpty(inputBox.Text);
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            _minecraft.WriteInput(inputBox.Text);
            inputBox.Text = string.Empty;
        }
    }
}